package Thread;

public class Demo2 {
    private int[] array=new int[1000];
    private int head=0;
    private int tail=0;
    private int size=0;
    private volatile Object lock=new Object();

    private Demo2(int val) {
        array=new int[val];
    }

    public void put(int val) throws InterruptedException {
        synchronized(lock){
            while(size==array.length){
                lock.wait();
            }
            array[tail]=val;
            tail++;
            if(tail==array.length){
                tail=0;
            }
            size++;
            
            lock.notify();

        }
    }

    public int take() throws InterruptedException{
        synchronized(lock){
            while(size==0){
                lock.wait();
            }
            
            int ret=array[head];
            head++;
            if(head==array.length){
                head=0;
            }
            size--;
            lock.notify();
           
            return ret;

        }
    }


    public static void main(String[] args) throws InterruptedException {

        Demo2 blockingQueue=new Demo2(1000);

        //生产者
        Thread t1=new Thread(()->{
            int count=0;
            while(true){
                try{
                    blockingQueue.put(count);
                    System.out.println("生产数据" + count);
                    count++;         
                    Thread.sleep(500);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        });

        //消费者
        Thread t2=new Thread(()->{
            while(true){
                try{
                    int ret=blockingQueue.take();
                    System.out.println("消费数据" + ret);
                    
                }catch(InterruptedException e){
                    e.printStackTrace(); 
                }
            }
        });

        t1.start();
        t2.start();
    }



    
}
